package com.hyfrogx.modules.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.hyfrogx.common.base.BaseServiceImpl;
import com.hyfrogx.common.base.QueryForm;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.modules.sys.entity.SysConfigEntity;
import com.hyfrogx.modules.sys.redis.SysConfigRedis;
import com.hyfrogx.modules.sys.dao.SysConfigDao;
import com.hyfrogx.modules.sys.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 系统配置信息
 *
 * @author wanglei
 * @date 2019-06-03 17:57:00
 */
@Service("sysConfigService")
public class SysConfigServiceImpl extends BaseServiceImpl<SysConfigDao, SysConfigEntity> implements SysConfigService {

	@Autowired
	private SysConfigRedis sysConfigRedis;

	@Override
	public String getIdKey() {
		return "id";
	}

	@Override
	public String getEntityName() {
		return "系统配置信息";
	}

	@Override
	public List<String> getUpdateIgnoreKey() {
		return CollUtil.newArrayList("paramKey");
	}

	@Override
	public void beforeSaveEntity(SysConfigEntity entity) {
		super.beforeSaveEntity(entity);
		if (retBool(
				this.count(
						new QueryWrapper<SysConfigEntity>()
								.eq("param_key", entity.getParamKey())
				)
		)) {
			throw new MyException("参数名已存在");
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteByIdList(Long userId, List<Long> configIds) {
		if (CollUtil.isEmpty(configIds)) {
			return true;
		}
		//删除配置
		List<String> list = CollUtil.newArrayList();
		for (Long id : configIds) {
			SysConfigEntity config = this.getById(id);
			if (ObjectUtil.isNull(config)) {
				throw new MyException(StrUtil.format("【{}】{}状态异常", id, getEntityName()));
			}
			list.add(config.getParamKey());
		}
		sysConfigRedis.delete(list);
		return super.deleteByIdList(userId, configIds);
	}

	@Override
	public QueryWrapper<SysConfigEntity> getSelectWrapper(QueryForm<SysConfigEntity> form, boolean isOrder) {
		return form.getWrapper(isOrder);
	}

	//oss

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateValueByKey(String key, String value) {
		boolean result = this.update(
				new UpdateWrapper<SysConfigEntity>()
						.set("param_value", value)
						.eq("param_key", key)
		);
		if (result) {
			sysConfigRedis.delete(key);
		} else {
			throw new MyException("更新参数失败");
		}
	}

	@Override
	public String getValue(String key) {
		SysConfigEntity config = sysConfigRedis.get(key);
		if (config == null) {
			config = this.queryByKey(key);
			sysConfigRedis.saveOrUpdate(config);
		}
		return config == null ? null : config.getParamValue();
	}

	/**
	 * 根据key，查询value
	 *
	 * @param paramKey
	 * @return
	 */
	private SysConfigEntity queryByKey(String paramKey) {
		return this.getOne(
				new QueryWrapper<SysConfigEntity>()
						.eq("param_key", paramKey)
				, false
		);
	}

	@Override
	public <T> T getConfigObject(String key, Class<T> clazz) {
		String value = getValue(key);
		if (StrUtil.isNotBlank(value)) {
			return new Gson().fromJson(value, clazz);
		}

		try {
			return clazz.newInstance();
		} catch (Exception e) {
			throw new MyException("获取参数失败");
		}
	}
}
